<?php
/**
 * Created by PhpStorm.
 * User: wangxiaodan
 * Date: 2017/5/14
 * Time: 下午2:29
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\Models\Children;
use Carbon\Carbon;
use Illuminate\Http\Request;

class ChildrenController extends Controller
{
    public function index(Request $request){
        $name = '';
        if ($request->isMethod('post')){
            $name = $request->table_search;
        }
        $children = Children::where('name', 'like', '%'.$name.'%')->orderBy('status', 'desc')->orderBy('id', 'desc')->paginate(config("constants.page_num"));
        return view('admin.children.index', compact('children'));
    }

    public function create(){
        return view('admin.children.create');
    }

    public function store(Requests\ChildrenRequest $request){
        $data = $request->all();
        $data['birthday'] = Carbon::parse($data['birthday']);
        $result = Children::create($data);
        if ($result){
            exit(json_encode(array('code'=>1, 'url'=>'/admin/children/')));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>$result)));
        }
    }

    public function edit($id){
        $child = Children::findOrFail($id);
        return view('admin.children.edit', compact('child'));
    }

    public function update(Requests\ChildrenRequest $request, $id){
        $child = Children::findOrFail($id);
        $result = $child->update($request->all());
        if ($result){
            exit(json_encode(array('code'=>1, 'url'=>'/admin/children/')));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>$result)));
        }
    }

    public function destroy($id){
        $child = Children::findOrFail($id);
        $child->status = 0;
        $child->classes_id = null;
        if ($child->save()){
            exit(json_encode(array('code'=>1)));
        } else {
            exit(json_encode(array('code'=>0)));
        }
    }

    public function findChildren(){
        $children = Children::get()->toArray();
        foreach ($children as $child){
            $result[] = array(
                'id'    => $child['id'],
                'value' => $child['name'],
            );
        }
        return json_encode($result);
    }

    public function findOne($id){
        return Children::find($id)->toJson();
    }

    public function addChild($id){
        return view('admin.children.addChild', compact('id'));
    }

    public function childToClasses(Request $request, $id){
        $child_id = $request->input('c_id');
        $child = Children::findOrFail($child_id);
        $child->classes_id = $id;
        if ($child->status == 0){ $child->status = 1; };
        $result = $child->save();
        if ($result){
            exit(json_encode(array('code'=>1, 'url'=>'/admin/classes')));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>$result)));
        }
    }
}